using System;
using System.ComponentModel;
using System.Drawing.Design;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using twistmachinev2.Business;

namespace twistmachinev2.TwistControl
{
    /// <summary>
    /// PropertyName属性的自定义编辑器
    /// 提供OPC UA节点选择功能
    /// </summary>
    public class PropertyNameEditor : UITypeEditor
    {
        /// <summary>
        /// 获取编辑器样式
        /// </summary>
        /// <param name="context">类型描述符上下文</param>
        /// <returns>编辑器样式</returns>
        public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
        {
            // 返回模态对话框样式
            return UITypeEditorEditStyle.Modal;
        }

        /// <summary>
        /// 编辑值
        /// </summary>
        /// <param name="context">类型描述符上下文</param>
        /// <param name="provider">服务提供者</param>
        /// <param name="value">当前值</param>
        /// <returns>编辑后的值</returns>
        public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            // 获取窗口服务
            var windowsFormsEditorService = provider?.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService;
            if (windowsFormsEditorService == null)
            {
                return value;
            }

            try
            {
                // 创建节点选择器窗体
                using (var nodeSelector = new FrmNodeSelector())
                {
                    // 如果当前有值，可以在选择器中预选
                    var currentValue = value as string;
                    
                    // 显示选择器对话框
                    var result = windowsFormsEditorService.ShowDialog(nodeSelector);
                    
                    if (result == DialogResult.OK && nodeSelector.SelectedNode != null)
                    {
                        // 返回选中的PropertyName
                        return nodeSelector.SelectedPropertyName;
                    }
                }
            }
            catch (Exception ex)
            {
                // 如果出现异常，显示错误信息
                MessageBox.Show($"打开节点选择器失败22：{ex.Message}", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            // 如果取消或出错，返回原值
            return value;
        }

        /// <summary>
        /// 指示编辑器是否支持绘制值的表示形式
        /// </summary>
        /// <param name="context">类型描述符上下文</param>
        /// <returns>如果支持绘制则返回true</returns>
        public override bool GetPaintValueSupported(ITypeDescriptorContext context)
        {
            return false;
        }
    }
}